package com.ai.module.chat.config.advice.exception;

import com.ai.module.chat.common.constant.RedisKeyStringConstant;
import com.ai.module.chat.common.constant.StringConstant;
import com.ai.module.chat.util.RedisTemplateUtils;
import com.ai.module.user.domain.vo.UserLoginInfo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: MrHe
 * @create: 2023-11-23 21:53
 * @description:
 **/
@Data
@Slf4j
public class BusinessException extends RuntimeException{

    String msg;

    int code = 500;

    public BusinessException(String msg) {
        super(msg);
    }

    public BusinessException(String msg, int code) {
        super(msg);
        this.code=code;
        logNoLogin(code);
    }
    public BusinessException(int code, String msg) {
        super(msg);
        this.code=code;
        logNoLogin(code);
    }

    private static void logNoLogin(int code) {
        if (code ==401){
            // 获取 用户 requets
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes==null || attributes.getRequest()==null){
                log.error("用户登录失败,attributes [{}]",attributes);
                return;
            }
            HttpServletRequest request = attributes.getRequest();

            String requestURI = request.getRequestURI();
            String headerToken = request.getHeader(StringConstant.TOKEN);
            if (StringUtils.isEmpty(headerToken)){
                log.error("用户登录失败,headerToken [{}],requestURI [{}]",headerToken,requestURI);
                return;
            }
            UserLoginInfo userToken = RedisTemplateUtils.get(String.format(RedisKeyStringConstant.USER_INFO, headerToken));
            log.error("用户登录失败, UserLoginInfo [{}] ,headerToken [{}],requestURI [{}]", userToken,headerToken,requestURI);

        }
    }

}
